# cron_job_handler.py - Run the dgrs in response to the cron job.
# Copyright 2009 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import glob
import logging
import os
import random
import yaml

try:
    from google.appengine.api.taskqueue import Task
except:
    from google.appengine.api.labs.taskqueue import Task

def main():   
    print 'Content-Type: text/plain'
    print ''
    yaml_file_text = file('./config.yaml').read()
    config = yaml.safe_load(yaml_file_text)
    if (type(config) != type({})):
        raise Exception, "config.yaml format incorrect" 
    run_probability = int(config.get('run_probability', "10"))
    dgrs_path = config.get('path_to_dgrs', './dgrs')
    dgrs = glob.glob (os.path.join (dgrs_path, '*.yaml'))
    print 'dgr count ' + str(len(dgrs))
    if (len(dgrs) == 0):
        logging.error('No dgr yaml files present in dgrs directory: ' + 
                      dgrs_path)
    for dgr in dgrs:
        print dgr
        if (random.randint(1, run_probability) == 1):
            print 'running ' + dgr
            dgr_task = Task(url='/run-dgr', method='POST',
                            params={'dgr-yaml-path': dgr})
            dgr_task.add('dgr-queue')

    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
